package com.library.guard.core.ws;

import com.alibaba.fastjson2.JSON;
import com.library.guard.core.config.GuardServerEndpointConfig;
import com.library.guard.core.config.N01Config;
import com.library.guard.core.domain.AlarmWsData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Package: com.library.guard.controller
 * @ClassName: AlarmWebSocketController
 * @Author: Yin
 * @Date: 15:47
 * @Description: 智能门禁报警
 */
@Slf4j
@Component
@ServerEndpoint(value = "/ws/guard/alarm" , configurator = GuardServerEndpointConfig.class)
public class AlarmWebSocketEndpoint {

    /** 当前所有连接 */
    private static final Map<String, Session> conns = new ConcurrentHashMap<>();

    private String uuid;

    @OnOpen
    public void onOpen(Session session,EndpointConfig sec) {
        String uuid = (String)sec.getUserProperties().get(N01Config.WS_CONNECTED);
        this.uuid = uuid;
        conns.put(uuid,session);
        log.info("[智能门禁WS]已连接");
    }

    @OnClose
    public void onClose(Session session) {
        conns.remove(uuid);
        log.info("[智能门禁WS]客户端已断开");
    }

    @OnError
    public void onError(Session session,Throwable throwable) {
        conns.remove(uuid);
        log.error("[智能门禁WS]客户端连接异常：{}",throwable.toString());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("[智能门禁WS]客户端传来消息：[{}]",message);
        session.getAsyncRemote().sendText("HEARTBEAT");
    }

    /** 发送消息 */
    public void sendAlarm(List list) {
        AlarmWsData alarmWsData = new AlarmWsData();
        alarmWsData.setList(list);
        if(conns.size() > 0 ) {
            conns.values().forEach(session -> {
                try {
                    // 异步发送
                    session.getAsyncRemote()
                        .sendText(JSON.toJSONString(alarmWsData));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

}
